package org.litu.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import org.litu.app.constant.SysContant;
import org.litu.app.dao.SysUserMapper;
import org.litu.app.entity.system.SysUser;
import org.litu.app.entity.system.SysUserLogin;
import org.litu.app.service.ISysFilesService;
import org.litu.app.service.ISysUserLoginService;
import org.litu.app.service.ISysUserRoleService;
import org.litu.app.service.ISysUserService;
import org.litu.base.service.IBaseUserService;
import org.litu.base.service.impl.BaseServiceImpl;
import org.litu.core.exception.LtParamException;
import org.litu.core.login.PasswordUtil;
import org.litu.core.login.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * user服务实现类
 * </p>
 *
 * @author ltgk
 * @since 2018-10-17
 */
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper, SysUser> implements ISysUserService, IBaseUserService {

    @Autowired
    private ISysUserLoginService userLoginService;
    @Autowired
    private ISysFilesService sysFilesService;
    @Autowired
    private ISysUserRoleService userRoleService;

    @Override
    public void beforeList(UserInfo user, SysUser entity, String keyword, Map<String, String> params, LambdaQueryWrapper<SysUser> query) {
        super.beforeList(user, entity, keyword, params, query);
        query.and(q -> q.like(SysUser::getAccount, keyword)
                .or().like(SysUser::getName, keyword)
                .or().like(SysUser::getPhone, keyword));
        if (StringUtils.isNotBlank(entity.getDeptId())) {
            query.eq(SysUser::getDeptId, entity.getDeptId());
        }
        query.eq(SysUser::getDeleteFlag, SysContant.FLAG_FALSE);
        query.orderByAsc(SysUser::getSortNum);
    }

    @Override
    public void beforePage(UserInfo user, SysUser entity, String keyword, IPage<SysUser> page, Map<String, String> params, LambdaQueryWrapper<SysUser> query) {
        super.beforePage(user, entity, keyword, page, params, query);
        query.and(q -> q.like(SysUser::getAccount, keyword)
                .or().like(SysUser::getName, keyword)
                .or().like(SysUser::getPhone, keyword));
        if (StringUtils.isNotBlank(entity.getDeptId())) {
            query.eq(SysUser::getDeptId, entity.getDeptId());
        }
        query.eq(SysUser::getDeleteFlag, SysContant.FLAG_FALSE);
        query.orderByAsc(SysUser::getSortNum);
    }

    /**
     * 用户添加的方法
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(UserInfo user, SysUser entity, Map<String, String> params) {
        // 保存用户信息
        if (!super.save(user, entity, params)) {
            throw new LtParamException("用户信息保存失败！");
        }

        // 添加用户的角色信息
        String roleIds = params.get("roleIds");
        if (!userRoleService.save(entity.getId(), roleIds)) {
            throw new LtParamException("用户信息保存失败！");
        }

        // 创建用户的密码信息
        SysUserLogin sysUserLogin = new SysUserLogin();
        String sKey = PasswordUtil.getSecretKey();
        sysUserLogin.setSecretKey(sKey);
        try {
            sysUserLogin.setPassword(PasswordUtil.getDbPassword(sKey));
        } catch (Exception e) {
            throw new LtParamException("生成用户密码错误！");
        }
        sysUserLogin.setEnableLogin(SysContant.FLAG_TRUE);
        // TODO 这里默认用户都是允许多点登陆的。
        sysUserLogin.setMultiuserLogin(0);
        sysUserLogin.setUserId(entity.getId());
        sysUserLogin.setLogonCount(0);
        sysUserLogin.setLoginStatus(SysContant.FLAG_TRUE);
        return userLoginService.save(sysUserLogin);
    }

    @Override
    public boolean update(UserInfo user, SysUser entity, Map<String, String> params) {
        // 修改用户信息
        if (!super.update(user, entity, params)) {
            throw new LtParamException("用户信息更新失败！");
        }

        // 修改用户的角色信息
        // 至少要有一个角色
        String roleIds = params.get("roleIds");
        if (StringUtils.isNotBlank(roleIds)) {
            userRoleService.removeByUserId(entity.getId());
        }
        return userRoleService.save(entity.getId(), roleIds);
    }

    /**
     * 用户信息逻辑删除，冻结
     *
     * @param id 用户的id信息
     * @return
     */
    @Override
    public boolean logicDelete(UserInfo user, String id) {
        // 用户信息校验
        LambdaQueryWrapper<SysUser> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysUser::getId, id);
        queryWrapper.eq(SysUser::getDeleteFlag, SysContant.FLAG_FALSE);
        SysUser nowUser = getOne(queryWrapper);
        if (nowUser == null) {
            throw new LtParamException("用户信息不存在，请确认!");
        }

        // 设置用户为删除状态
        nowUser.setDeleteFlag(SysContant.FLAG_TRUE);
        nowUser.setDeleteBy(user.getId());
        nowUser.setDeleteTime(new Date());
        return updateById(nowUser);
    }

    /**
     * 根据账户名查找用户 在用户登录时使用， 只有当账户存在，并且可用是才会返回用户信息。
     *
     * @param account
     * @return
     */
    @Override
    public SysUser getByAccount(String account) {
        LambdaQueryWrapper<SysUser> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysUser::getAccount, account);
        SysUser user = getOne(queryWrapper);

        return user;
    }


    /**
     * 更换当前登陆用户头像
     *
     * @param userId
     * @param photoId 用户头像ID
     * @return 如果替换成功，则返回true
     */
    @Override
    public boolean updatePhoto(String userId, String photoId) {
        SysUser sysUser = getById(userId);
        //原头像删除
        String oldPhotoId = sysUser.getPhoto();
        if (StringUtils.isNotBlank(oldPhotoId)) {
            // 删除这部分的异常忽略掉。
            try {
                sysFilesService.delete(oldPhotoId, null);
            } catch (Exception e) {
            }
        }
        sysUser.setPhoto(photoId);
        return updateById(sysUser);
    }

    /**
     * 用户账号查重
     *
     * @param userId  当前用户的ID，在用户修改登陆账号时使用到
     * @param account 当前的账号信息
     * @return 返回true标识存在重复，返回false标识没有重复
     */
    @Override
    public boolean accountCheck(String userId, String account) {
        LambdaQueryWrapper<SysUser> queryWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(userId)) {
            queryWrapper.ne(SysUser::getId, userId);
        }
        queryWrapper.eq(SysUser::getAccount, account);

        int res = count(queryWrapper);

        return res > 0;
    }

    /**
     * 公共平台需要的方法
     *
     * @param userId
     * @return
     */
    @Override
    public String getNameByUserId(String userId) {
        SysUser user = baseMapper.selectById(userId);
        return null == user ? "" : user.getName();
    }
}
